package com.gwtgeo.service.dao.jdbc;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.gwtgeo.service.dao.LocationDao;
import com.gwtgeo.service.model.Location;

public class LocationDaoJdbc implements LocationDao {

	private DataSource dataSource;

	private RowMapper rowMapper;

	public boolean exists(Long id) {
		return false;
	}

	public Location get(Long id) {
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<Location> getAll() {

		final String sql = "select id,name,geom from location";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		return jdbcTemplate.query(sql, rowMapper);

	}

	public void remove(Long id) {
	}

	public Location save(Location id) {
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<Location> findByName(String name) {
		final String sql = "select id,name,geom from location where SP_ASCII(name) ilike SP_ASCII( ? )";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		return jdbcTemplate.query(sql, new Object[] { "%" + name + "%" },
				rowMapper);
	}

	@SuppressWarnings("unchecked")
	public List<Location> findByCoordinates(Double latitude, Double longitude) {
		final String sql = "select id,name,geom from location where geom ~= ST_GeomFromText( ? ,4326)";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		return jdbcTemplate.query(sql, new Object[] { "POINT( " + longitude
				+ " " + latitude + " )" }, rowMapper);
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public void setRowMapper(RowMapper rowMapper) {
		this.rowMapper = rowMapper;
	}
}
